package com.xiaoyu.studyworkspace.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.xiaoyu.studyworkspace.common.kapaentity.userinfo.RootBean;
import com.xiaoyu.studyworkspace.common.kapaentity.websocket.KapaCode;
import com.xiaoyu.studyworkspace.common.util.KapaHttpUtil;
import com.xiaoyu.studyworkspace.common.util.KapaParam;
import com.xiaoyu.studyworkspace.common.util.PayUtil;
import com.xiaoyu.studyworkspace.common.kapaentity.userinfo.RecordInfo;
import com.xiaoyu.studyworkspace.mapper.UserMapper;
import com.xiaoyu.studyworkspace.pojo.User;
import com.xiaoyu.studyworkspace.properties.UserCheckKapaProperties;
import com.xiaoyu.studyworkspace.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCheckKapaProperties userCheckKapaProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public String checkUser(String relationInfo) {
        //调用接口
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put(KapaParam.CODE, userCheckKapaProperties.getCode());
        paramMap.put(KapaParam.DATA, userCheckKapaProperties.getData());
        paramMap.put(KapaParam.DEPLOY_APP_ID, userCheckKapaProperties.getDeploy_app_id());
        paramMap.put(KapaParam.INIT_ID, userCheckKapaProperties.getInit_id());
        paramMap.put(KapaParam.SESSION_ID, userCheckKapaProperties.getSession_id());
        String responseResult = HttpUtil.post(KapaCode.URL, KapaHttpUtil.convertParam(paramMap));
        RootBean kapaRecord = JSONUtil.toBean(responseResult, RootBean.class);
        List<RecordInfo> recordList = kapaRecord.getData().getRecord_list();
        for (RecordInfo recordInfo : recordList) {
            if (recordInfo.getRelation_info().equals(relationInfo)) {
                //查询数据库，没有该用户则写入
                String time = recordInfo.getTime();
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime localDateTime = LocalDateTime.parse(time, formatter);
                Duration duration = Duration.between(localDateTime, now);
                long days = duration.toMinutes() / 60 / 24;
                if (days >= 20) {
                    //说明过期了
                    //去数据库中删除
                    return "";
                }
                User userIsExist = userMapper.selectUserById(relationInfo);
                Double payCount = Double.valueOf(recordInfo.getValue());
                if (userIsExist == null) {
                    User user = new User();
                    user.setRelation_info(recordInfo.getRelation_info());
                    user.setPay_count(recordInfo.getValue());
                    user.setCreate_time(localDateTime);
                    //写入缓存
                    //不管多少金额都转入数据库,已经转账的
                    userMapper.insertUser(user);
                }
                if (payCount >= PayUtil.PAY_COUNT) {
                    //写入缓存
                    return recordInfo.getRelation_info();
                }

            }
        }
        return "";
    }

    @Override
    public boolean haveRedis(String relationInfo) {
        String user = stringRedisTemplate.opsForValue().get(relationInfo);
        if (user != null) {
            //说明缓存当中存在，则为true
            return true;
        }
        return false;
    }

    @Override
    public User findUser(String relationInfo) {
        User user = new User();
        //先从缓存当中查询
        List<User> usersRedis = (List<User>) redisTemplate.opsForValue().get("users");
        if (usersRedis != null) {
            for (User usersRedi : usersRedis) {
                if (relationInfo.equals(usersRedi.getRelation_info())) {
                    //时间检查
                    LocalDateTime createTime = usersRedi.getCreate_time();
                    LocalDateTime now = LocalDateTime.now();
                    Duration duration = Duration.between(createTime, now);
                    long days = duration.toMinutes() / 60 / 24;
                    if (days >= 20) {
                        //说明过期了
                        return null;
                    }
                    //相同说明存在支付
                    //判断支付的个数
                    Double payCount = Double.valueOf(usersRedi.getPay_count());
                    if (payCount >= PayUtil.PAY_COUNT) {
                        BeanUtils.copyProperties(usersRedi, user);
                        return user;
                    }
                }
            }
        }
        //如果缓存当中不存在，去数据库查询
        List<User> userList = userMapper.selectAllUser();
        if (userList != null) {
            for (User user1 : userList) {
                if (relationInfo.equals(user1.getRelation_info())) {
                    //时间检查
                    LocalDateTime createTime = user1.getCreate_time();
                    LocalDateTime now = LocalDateTime.now();
                    Duration duration = Duration.between(createTime, now);
                    long days = duration.toMinutes() / 60 / 24;
                    if (days >= 20) {
                        //说明过期了
                        return null;
                    }
                    //相同说明存在支付
                    //判断支付的个数
                    Double payCount = Double.valueOf(user1.getPay_count());
                    if (payCount >= PayUtil.PAY_COUNT) {
                        BeanUtils.copyProperties(user1, user);
                        return user;
                    }
                }
            }
        }
        //数据库写入，存不存在都写入缓存种
        redisTemplate.opsForValue().set("users", userList);
        return null;
    }
}
